/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-07-09
*/
package com.rzico.market.service;

import com.alibaba.fastjson.JSON;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.*;
import com.rzico.basics.plugin.jd.JDProductInfo;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.basics.plugin.jd.JDStockInfo;
import com.rzico.basics.service.*;
import com.rzico.core.entity.SysMsgPush;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.service.SysMsgPushService;
import com.rzico.core.service.SysPluginService;
import com.rzico.market.entity.MarketProduct;
import com.rzico.market.plugin.yanxuan.YXOpenApiUtils;
import com.rzico.util.CodeGenerator;
import com.rzico.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.market.mapper.MarketProductMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 第三方产品档案业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class MarketProductService extends BaseServiceImpl<MarketProduct, String> {

    @Autowired
    private MarketProductMapper marketProductMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    protected SysPluginService sysPluginService;

    @Autowired
    private SysMsgPushService sysMsgPushService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SupplierService supplierService;

    @Override
    public BaseMapper<MarketProduct, String> getMapper() {
        return marketProductMapper;
    }

    /**
     * 查询所有京东商品的sku
     * @return
     */
    public List<String> selectSkuList(Map<String, Object> params){
        return marketProductMapper.selectSkuList(params);
    }

    /**
     * 京东商品sku组合成单个商品
     * @param skuInfoList
     * @param supplierId
     * @param code
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<MarketProduct> jdProductCompose(List<Map<String, Object>> skuInfoList, String supplierId, String code){
        List<MarketProduct> allMarketProductList = new ArrayList<MarketProduct>();
        boolean isListSign = false;//标识sku是否展示
        for (Map<String, Object> map : skuInfoList) {
            if ("1".equals(map.get("isList").toString())) {
                isListSign = true;
            }
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("skuId", map.get("sku"));
            param.put("supplierId", supplierId);
            List<MarketProduct> marketProductList = super.selectList(param);
            MarketProduct marketProduct = marketProductList.get(0);
            if (StringUtils.isEmpty(marketProduct.getGoodId())) {
                marketProduct.setSpec1(map.get("spec1").toString());
                marketProduct.setSpec2(map.get("spec2").toString());
                if ("1".equals(map.get("isList").toString())) {
                    marketProduct.setIsList(true);
                } else {
                    marketProduct.setIsList(false);
                }
                allMarketProductList.add(marketProduct);
            } else {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("goodId", marketProduct.getGoodId());
                params.put("supplierId", supplierId);
                List<MarketProduct> mList = super.selectList(params);
                for (MarketProduct m : mList) {
                    if (m.getSkuId().equals(map.get("sku").toString())) {
                        m.setSpec1(map.get("spec1").toString());
                        m.setSpec2(map.get("spec2").toString());
                        if ("1".equals(map.get("isList").toString())) {
                            m.setIsList(true);
                        } else {
                            m.setIsList(false);
                        }
                        break;
                    }
                }
                allMarketProductList.addAll(mList);
            }
        }
        for (int i = 0; i < allMarketProductList.size(); i ++){
            if (!isListSign) {
                if (0 < i) {
                    allMarketProductList.get(i).setIsList(false);
                } else {
                    allMarketProductList.get(i).setIsList(true);
                }
            }
            allMarketProductList.get(i).setGoodId(code);
            super.updateByPrimaryKeySelective(allMarketProductList.get(i));
        }
        return allMarketProductList;
    }

    /**
     * 京东商品上架
     * 1.单sku商品直接添加
     * 2.包含该sku的商品，该商品下的所有sku集合均未添加，亦直接添加
     * 3.包含该sku的商品中，部分sku已添加，部分未添加
     * @param skuList 待上传的京东sku列表
     * @param enterprise 商户id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<MarketProduct> jdProductShelf(List<String> skuList, Enterprise enterprise, String supplierId){
        List<MarketProduct> result = new ArrayList<MarketProduct>();//返回结果
        //上架时设置为其他分类
        Long cateGoryId = 0L;
        Map<String, Object> categoryParam = new HashMap<String, Object>();
        categoryParam.put("name", "自营");
        List<ProductCategory> categoryList = productCategoryService.selectList(categoryParam);
        if (0 < categoryList.size()) {
            cateGoryId = categoryList.get(0).getId();
        }
        //设置标签
        Long[] tagIds = new Long[]{};
        for (String sku : skuList) {
            List<MarketProduct> addMarketProductList = new ArrayList<MarketProduct>();//待添加至商品库的所有商品集合
            List<Product> addProductList = new ArrayList<Product>();
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("skuId", sku);
            param.put("supplierId", supplierId);
            List<MarketProduct> marketProductSkuList = super.selectList(param);
            if (StringUtils.isEmpty(marketProductSkuList.get(0).getGoodId())) {
                boolean hasAdd = false;//是否已经添加
                Map<String, Object> productParam = new HashMap<String, Object>();
                productParam.put("sn", sku);
                List<Product> productList = productService.selectList(productParam);
                for (Product p : productList) {
                    if (p.getSn().equals(marketProductSkuList.get(0).getSn())) {
                        hasAdd = true;
                    }
                }
                if (hasAdd) {
                    continue;
                }
                //goodId为空说明该商品为单sku，直接添加
                addProductList = setProductInfo(marketProductSkuList, enterprise, cateGoryId);
                productService.insertProduct(addProductList, tagIds);
                result.addAll(marketProductSkuList);
            } else {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("goodId", marketProductSkuList.get(0).getGoodId());
                params.put("supplierId", supplierId);
                List<MarketProduct> mList = super.selectList(params);
                //判断同个商品的sku是否已有添加至商品sku库，若已添加部分，则取商品库的goodId，将未添加的添加至商品库，若所有sku均未添加，则将所有的sku集合添加
                Long goodId = 0L;//商品库的商品id
                boolean hasAddPart = false;
                for (MarketProduct m : mList) {
                    if (m.getIsShelf()) {
                        if (!hasAddPart) {
                            hasAddPart = true;
                            Map<String, Object> productParam = new HashMap<String, Object>();
                            productParam.put("sn", m.getSn());
                            productParam.put("enterpriseId", enterprise.getId());
                            List<Product> pList = productService.selectList(productParam);
                            goodId = pList.get(0).getGoodsId();
                            //判断该sku是否展示，若展示，则将商品库的sku展示改为不展示
                            if (marketProductSkuList.get(0).getIsList()) {
                                for (Product p : pList) {
                                    p.setIsList(false);
                                    productService.updateByPrimaryKey(p);
                                }
                            }
                        }
                    } else {
                        boolean hasAdd = false;//是否已经添加
                        Map<String, Object> productParam = new HashMap<String, Object>();
                        productParam.put("sn", sku);
                        List<Product> productList = productService.selectList(productParam);
                        for (Product p : productList) {
                            if (p.getSn().equals(m.getSn())) {
                                hasAdd = true;
                            }
                        }
                        if (hasAdd) {
                            continue;
                        }
                        addMarketProductList.add(m);
                    }
                }
                addProductList = setProductInfo(addMarketProductList, enterprise, cateGoryId);
                if (hasAddPart) {
                    for (Product p : addProductList) {
                        p.setGoodsId(goodId);
                    }
                    productService.insertList(addProductList);
                } else {
                    productService.insertProduct(addProductList, tagIds);
                }
                result.addAll(addMarketProductList);
            }
        }
        return result;
    }

    /**
     * 将京东商品信息填充至商品信息中
     * @param marketProductList 京东商品信息
     * @param enterprise 商品信息
     * @param cateGoryId 分类id
     * @return
     */
    public List<Product> setProductInfo(List<MarketProduct> marketProductList, Enterprise enterprise, Long cateGoryId) {
        List<Product> productList = new ArrayList<Product>();
        for (MarketProduct m : marketProductList) {
            Product p = new Product();
            //创建日期
            p.setCreateDate(new Date());
            //成本价
            p.setCost(m.getCost());
            //是否删除
            p.setDeleted(false);
            //是否列出--第一个展示，其余的不展示
            p.setIsList(m.getIsList());
            //是否上架
            p.setIsMarketable(false);
            //是否有视频，否
            p.setIsMetaVideo(false);
            //市场价
            p.setMarketPrice(m.getMarketPrice());
            //商品名称
            p.setName(m.getName());
            //销售价
            p.setPrice(m.getPrice());
            //sn，对应京东sku
            p.setSn(m.getSn());
            //单位
            p.setUnit(m.getUnit());
            //单位转换系数
            p.setUnitRate(m.getUnitRate());
            //VIP1-5价格
            p.setVip1price(BigDecimal.ZERO);
            p.setVip2price(BigDecimal.ZERO);
            p.setVip3price(BigDecimal.ZERO);
            p.setVip4price(BigDecimal.ZERO);
            p.setVip5price(BigDecimal.ZERO);
            //重量
            p.setWeight(m.getWeight());
            //缩略图--加图片路径
            p.setThumbnail(m.getThumbnail());
            //已分配库存
            p.setAllocatedStock(0);
            //当前库存--暂设200
            p.setStock(100);
            //类型，0.实物
            p.setType(0);
            //业务
            p.setSubType(0);
            //保质期
            p.setQuality(0);
            //最小起订量
            p.setMinLimit(0);
            //日限量
            p.setMaxLimit(0);
            //
            p.setPublishType(0);
            //分类
            p.setProductCategoryId(cateGoryId);
            //规格
            p.setSpec1(m.getName());
            //描述
            p.setSubTitle(m.getSubTitle());
            //供应商
            p.setSupplierId(m.getSupplierId());
            //归属企业
            p.setEnterpriseId(enterprise.getId());
            //设置商品图片
            p.setMeta(m.getMeta());
            //设置商品详情图
            p.setContent(m.getContent());
            //设置税率,采用京东与我司的结算税率
            if (null != m.getTax()) {
                p.setTax(m.getTax());
            } else {
                p.setTax(new BigDecimal(0));
            }
            //查看京东商品品牌是否已经保存于品牌表中，未保存则新建
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("name", "jd-" + m.getBrandName());
            List<Brand> brandList = brandService.selectList(params);
            if (0 < brandList.size()) {
                p.setBrandId(brandList.get(0).getId());
            } else {
                Brand b = new Brand();
                b.setCreateDate(new Date());
                b.setName("jd-" + m.getBrandName());
                b.setDeleted(false);
                b.setEnterpriseId(enterprise.getId());
                brandService.insertUseGeneratedKeys(b);
                p.setBrandId(b.getId());
            }
            productList.add(p);
            //已上架至商品库的商品更新isshelf状态
            m.setIsShelf(true);
            super.updateByPrimaryKey(m);
        }
        return productList;
    }

    /**
     * 1.调用京东商品池api获得京东实物商品sku列表，获取第三方商品池已保存的sku列表，
     * 2.对二者进行比较，第三方商品池中有无京东返回得sku列表
     * 3.若有，则新增商品sku信息，无则不添加商品信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveJDProductInfo(SysPlugin sysplugin){
        List <String> addSkuList = new ArrayList<String>();
        //商品池获取的京东sku列表
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sn", "jd-");
        List<String> dbSkuList = selectSkuList(params);
        //查询京东商品获取的sku列表
        List<String> skuList = JDServiceUtils.selectJDProSku(sysplugin.getAttribute("token"));
        if (0 == dbSkuList.size()){
            addSkuList = skuList;
        } else {
            addSkuList = JDServiceUtils.compareSku(dbSkuList, skuList);
        }
        List<MarketProduct> addMarketProductList = new ArrayList<MarketProduct>();
        if (0 < addSkuList.size()) {
            addMarketProductList = getJDProducts(sysplugin, addSkuList);
            for (MarketProduct m : addMarketProductList) {
                super.insertUseGeneratedKeys(m);
            }
        }
    }

    /**
     * 获取京东商品资料
     * @param sysPlugin
     * @param skuList
     * @return
     */
    public List<MarketProduct> getJDProducts(SysPlugin sysPlugin, List<String> skuList) {
        //调用京东获取商品信息接口
        List<JDProductInfo>  productList = JDServiceUtils.selectJDProduct(sysPlugin.getAttribute("token"), skuList);
        //保存的商品信息
        List<MarketProduct> marketProductList = new ArrayList<MarketProduct>();
        Long enterpriseId = 0L;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("name","葫芦派");
        List<Enterprise> enterpriseList= enterpriseService.selectList(param);
        if (0 < enterpriseList.size()) {
            enterpriseId = enterpriseList.get(0).getId();
        }
        Long supplierId = 0L;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name","京东");
        List<Supplier> supplierList = supplierService.selectList(params);
        if (0 < supplierList.size()) {
            supplierId = supplierList.get(0).getId();
        }
        //设置京东商品信息
        for (JDProductInfo jdp : productList) {
            MarketProduct marketProduct = new MarketProduct();
            //创建时间
            marketProduct.setCreateDate(new Date());
            //是否列出
            marketProduct.setIsList(true);
            //是否上架
            if ("1".equals(jdp.getState())) {
                marketProduct.setIsMarketable(true);
            } else {
                marketProduct.setIsMarketable(false);
            }
            //市场价
            marketProduct.setMarketPrice(BigDecimal.ZERO);
            //商品名称
            marketProduct.setName(jdp.getName());
            //描述说明
            marketProduct.setSubTitle(jdp.getShouhou());
            //销售价
            marketProduct.setPrice(BigDecimal.ZERO);
            //结算价
            marketProduct.setCost(BigDecimal.ZERO);
            //税率
            marketProduct.setTax(BigDecimal.ZERO);
            //sn
            marketProduct.setSn("jd-" + jdp.getSku());
            //售卖单位
            if (StringUtils.isNotEmpty(jdp.getSaleUnit())) {
                marketProduct.setUnit(jdp.getSaleUnit());
            } else {
                marketProduct.setUnit("件");
            }
            //单位系数,用默认
            marketProduct.setUnitRate(BigDecimal.ONE);
            //重量
            if (StringUtils.isNotEmpty(jdp.getWeight())) {
                marketProduct.setWeight(new BigDecimal(jdp.getWeight()));
            } else {
                marketProduct.setWeight(BigDecimal.ZERO);
            }
            //缩略图
            marketProduct.setThumbnail(sysPlugin.getAttribute("thumbnailPath") + jdp.getImagePath());
            //类型
            marketProduct.setType(0);
            //保质期
            marketProduct.setQuality(0);
            //商品详情
            if ("[]".equals(jdp.getWxintroduction())) {
                marketProduct.setContent(" ");
            } else {
                marketProduct.setContent(JDServiceUtils.getImageContent(jdp.getWxintroduction()));
            }
            //商品详情图
            marketProduct.setWxintroduction(jdp.getWxintroduction());
            //品牌名称
            marketProduct.setBrandName(jdp.getBrandName());
            //供应商
            marketProduct.setSupplierId(supplierId);
            //skuid
            marketProduct.setSkuId(jdp.getSku());
            //市场插件id
            marketProduct.setMarketPluginId(sysPlugin.getPluginId());
            //来源商户
            marketProduct.setEnterpriseId(enterpriseId);
            marketProductList.add(marketProduct);
        }

        return marketProductList;
    }

    /**
     * 更新已上架至商品库的第三方商品信息
     * 判断库存是否满200，商品的上下架状态及可售性，若京东返回库存不满200，不可售，下架，则直接商品下架，并发送通知
     * 判断商品结算价是否有改变，不将商品下降，发送通知即可
     * 商品名称改变下架，若主图与详情图改变则发送通知
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJDProductInfo(SysPlugin sysplugin, Long enterpriseId, String mchId, List<Product> productList) {
        if (0 < productList.size()) {
            List<SysMsgPush> sysMsgPushList = new ArrayList<SysMsgPush>();
            for (Product p : productList) {
                boolean updateProduct = false;//是否更新p的标志
                boolean offShelfSign = false;//商品下架标识
                //查询京东商品上下架接口
                JDProductInfo jdp1 = JDServiceUtils.selectJDProductState(sysplugin.getAttribute("token"), p.getSn().substring(3, p.getSn().length()));
                if ("0".equals(jdp1.getState())) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> content = new HashMap<>();
                        content.put("title", "京东商品上架状态改变");
                        content.put("sku", p.getSn());
                        content.put("name", p.getName());
                        content.put("msg", "每日商品库定时更新，商品处于下架状态,不可售卖系统已下架");
                        content.put("supplierName", "京东");
                        sysMsgPush.setMsgKey("msg-jingdongMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(content));
                        sysMsgPush.setMsgTitle(content.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setIsMarketable(false);
                    p.setModifyDate(new Date());
                    offShelfSign = true;
                    updateProduct = true;
                }
                //查询京东商品可售性接口
                JDProductInfo jdp2 = JDServiceUtils.selectJDProductSaleState(sysplugin.getAttribute("token"), p.getSn().substring(3, p.getSn().length()));
                if ("0".equals(jdp2.getSaleState()) || StringUtils.isEmpty(jdp2.getIsCanVAT()) || "0".equals(jdp2.getIsCanVAT())) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> content = new HashMap<>();
                        content.put("title", "京东商品可售性改变");
                        content.put("sku", p.getSn());
                        content.put("name", p.getName());
                        content.put("msg", "每日商品库定时更新，商品处于不可售状态,系统已下架");
                        content.put("supplierName", "京东");
                        sysMsgPush.setMsgKey("msg-jingdongMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(content));
                        sysMsgPush.setMsgTitle(content.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setIsMarketable(false);
                    p.setModifyDate(new Date());
                    offShelfSign = true;
                    updateProduct = true;
                }
                //根据sku查询信息，判断商品名称，主图，详情图是否有变（需转换），有变化进行更新
                JDProductInfo jdp4 = JDServiceUtils.selectJDProductInfo(sysplugin.getAttribute("token"), p.getSn().substring(3, p.getSn().length()));
                if (!p.getName().equals(jdp4.getName())) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> content = new HashMap<>();
                        content.put("title", "京东商品名称改变");
                        content.put("sku", p.getSn());
                        content.put("name", p.getName());
                        content.put("msg", "每日商品库定时更新，名称由" + p.getName() + "变为" + jdp4.getName() + ",系统已下架");
                        content.put("supplierName", "京东");
                        sysMsgPush.setMsgKey("msg-jingdongMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(content));
                        sysMsgPush.setMsgTitle(content.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setName(jdp4.getName());
                    p.setIsMarketable(false);
                    p.setModifyDate(new Date());
                    offShelfSign = true;
                    updateProduct = true;
                }
                //更新商品缩略图
                if (!p.getThumbnail().equals(sysplugin.getAttribute("thumbnailPath") + jdp4.getImagePath())){
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        p.setThumbnail(sysplugin.getAttribute("thumbnailPath") + jdp4.getImagePath());
                    }
                    updateProduct = true;
                }
                String content = JDServiceUtils.getImageContent(jdp4.getWxintroduction());
                if (!p.getContent().equals(content)) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> contentMap = new HashMap<>();
                        contentMap.put("title", "京东详情图改变");
                        contentMap.put("sku", p.getSn());
                        contentMap.put("name", p.getName());
                        contentMap.put("msg", "每日商品库定时更新，详情图由" + p.getContent() + "变为" + content + ",商品详情图已更新");
                        contentMap.put("supplierName", "京东");
                        sysMsgPush.setMsgKey("msg-jingdongMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                        sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setContent(content);
                    updateProduct = true;
                }
                String imageInfo = JDServiceUtils.selectJDProductImage(sysplugin.getAttribute("token"), p.getSn().substring(3, p.getSn().length()));
                String meta = JDServiceUtils.getImageMeta(imageInfo, sysplugin.getAttribute("imgPath"));
                if (!p.getMeta().equals(meta)) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> contentMap = new HashMap<>();
                        contentMap.put("title", "京东商品主图改变");
                        contentMap.put("sku", p.getSn());
                        contentMap.put("name", p.getName());
                        contentMap.put("msg", "每日商品库定时更新，主图由" + p.getMeta() + "变为" + meta + ",商品主图已更新");
                        contentMap.put("supplierName", "京东");
                        sysMsgPush.setMsgKey("msg-jingdongMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                        sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setMeta(meta);
                    updateProduct = true;
                }
                //若商品已下架，则无须查询商品库存信息及商品价格信息，因为若商品不可售，接口查不到信息
                if (!offShelfSign) {
                    //查询京东api库存接口，暂时以莆田市荔城区为配送地址,每天更新库存为200,库存不满200不可上架
                    String area = sysplugin.getAttribute("invoiceProvice") + "_" + sysplugin.getAttribute("invoiceCity")
                            + "_" + sysplugin.getAttribute("invoiceCounty");
                    Map<String, Object> skuParam = new HashMap<String, Object>();
                    skuParam.put("skuId", p.getSn().substring(3, p.getSn().length()));
                    skuParam.put("num", 100);
                    String skuNums = "[" + JSON.toJSONString(skuParam) + "]";
                    JDStockInfo stockInfo = JDServiceUtils.getStock(sysplugin.getAttribute("token"), skuNums, area);
                    if (!"33".equals(stockInfo.getStockStateId()) && !"39".equals(stockInfo.getStockStateId())
                            && !"40".equals(stockInfo.getStockStateId())) {
                        if (p.getIsMarketable() && !p.getDeleted()) {
                            SysMsgPush sysMsgPush = new SysMsgPush();
                            sysMsgPush.setId(CodeGenerator.getUUID());
                            sysMsgPush.setIsPush(false);
                            sysMsgPush.setMsgLevel(1);
                            sysMsgPush.setMsgType(4);
                            sysMsgPush.setReadStatus("2");
                            sysMsgPush.setPushStatus("0");
                            sysMsgPush.setMchId(mchId);
                            sysMsgPush.setSendDate(new Date());
                            sysMsgPush.setSendUserId("system");
                            sysMsgPush.setSendUserName("admin");
                            sysMsgPush.setReceiveUserName("system");
                            sysMsgPush.setReceiveUserId("yunyin");
                            sysMsgPush.setIsAttac("0");
                            Map<String, Object> contentMap = new HashMap<>();
                            contentMap.put("title", "京东商品库存不足");
                            contentMap.put("sku", p.getSn());
                            contentMap.put("name", p.getName());
                            contentMap.put("msg", "每日商品库定时更新库存不足100,系统已下架");
                            contentMap.put("supplierName", "京东");
                            sysMsgPush.setMsgKey("msg-jingdongMoudle");
                            sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                            sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                            sysMsgPushList.add(sysMsgPush);
                        }
                        //库存不满200直接下架
                        p.setIsMarketable(false);
                        p.setModifyDate(new Date());
                        updateProduct = true;
                    } else if (100 != p.getStock()) {
                        p.setStock(100);
                        p.setModifyDate(new Date());
                        updateProduct = true;
                    }
                    //查询商品价格信息，若成本价有变化，则更新
                    JDProductInfo jdp3 = JDServiceUtils.selectJDProductPrice(sysplugin.getAttribute("token"), p.getSn().substring(3, p.getSn().length()));
                    if (0 != p.getCost().compareTo(new BigDecimal(jdp3.getPrice()))) {
                        if (p.getIsMarketable() && !p.getDeleted()) {
                            SysMsgPush sysMsgPush = new SysMsgPush();
                            sysMsgPush.setId(CodeGenerator.getUUID());
                            sysMsgPush.setIsPush(false);
                            sysMsgPush.setMsgLevel(1);
                            sysMsgPush.setMsgType(4);
                            sysMsgPush.setReadStatus("2");
                            sysMsgPush.setPushStatus("0");
                            sysMsgPush.setMchId(mchId);
                            sysMsgPush.setSendDate(new Date());
                            sysMsgPush.setSendUserId("system");
                            sysMsgPush.setSendUserName("admin");
                            sysMsgPush.setReceiveUserName("system");
                            sysMsgPush.setReceiveUserId("yunyin");
                            sysMsgPush.setIsAttac("0");
                            Map<String, Object> contentMap = new HashMap<>();
                            contentMap.put("title", "京东商品结算价改变");
                            contentMap.put("sku", p.getSn());
                            contentMap.put("name", p.getName());
                            contentMap.put("msg", "每日商品库定时更新，结算价由" + p.getCost() + "变为" + jdp3.getPrice() + ",系统已下架");
                            contentMap.put("supplierName", "京东");
                            sysMsgPush.setMsgKey("msg-jingdongMoudle");
                            sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                            sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                            sysMsgPushList.add(sysMsgPush);
                        }
                        p.setMarketPrice(new BigDecimal(jdp3.getJdPrice()));
                        p.setPrice(new BigDecimal(jdp3.getPrice()));
                        p.setCost(new BigDecimal(jdp3.getPrice()));
                        p.setTax(new BigDecimal(jdp3.getTax()));
                        String tax = jdp3.getTax();
                        if (!"0".equals(tax)) {
                            p.setTax(new BigDecimal(tax).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            p.setTax(new BigDecimal(0));
                        }
                        p.setIsMarketable(false);
                        p.setModifyDate(new Date());
                        updateProduct = true;
                    }
                }
                if (updateProduct) {
                    productService.updateByPrimaryKey(p);
                }
            }
            if (0 < sysMsgPushList.size()) {
                for (SysMsgPush msg : sysMsgPushList) {
                    sysMsgPushService.insert(msg);
                }
            }
        }
    }

    /**
     * 更新第三方商品池的商品基础信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJDProductInfo(SysPlugin sysplugin, List<MarketProduct> marketProductList){
        //根据商品sku查询商品信息，除sku外，其他所有信息全部更新
        //根据京东商品sku获取商品可售性
        for (MarketProduct marketProduct : marketProductList) {
            JDProductInfo jdp = JDServiceUtils.selectJDProductInfo(sysplugin.getAttribute("token"), marketProduct.getSkuId());
            if (null != jdp) {
                //创建时间
                marketProduct.setModifyDate(new Date());
                //商品名称
                marketProduct.setName(jdp.getName());
                //描述说明
                marketProduct.setSubTitle(jdp.getShouhou());
                //售卖单位
                if (StringUtils.isNotEmpty(jdp.getSaleUnit()) && 0 != jdp.getSaleUnit().trim().length()) {
                    marketProduct.setUnit(jdp.getSaleUnit());
                } else {
                    marketProduct.setUnit("件");
                }
                //重量
                if (StringUtils.isNotEmpty(jdp.getWeight())) {
                    marketProduct.setWeight(new BigDecimal(jdp.getWeight()));
                } else {
                    marketProduct.setWeight(BigDecimal.ZERO);
                }
                //缩略图
                marketProduct.setThumbnail(sysplugin.getAttribute("thumbnailPath") + jdp.getImagePath());
                //商品详情
                if ("[]".equals(jdp.getWxintroduction())) {
                    marketProduct.setContent(" ");
                } else {
                    marketProduct.setContent(JDServiceUtils.getImageContent(jdp.getWxintroduction()));
                }
                //商品详情图
                marketProduct.setWxintroduction(jdp.getWxintroduction());
                //品牌名称
                marketProduct.setBrandName(jdp.getBrandName());
			/*//查询图片信息并保存
			String imageInfo = JDServiceUtils.selectJDProductImage(sysPlugin.getAttribute("token"), jdp.getSku());
			marketProduct.setImage(imageInfo);
			//其他资源
			marketProduct.setMeta(JDServiceUtils.getImageMeta(imageInfo, sysPlugin.getAttribute("imgPath")));*/
            }
        }
        //更新信息
        for (MarketProduct m : marketProductList) {
            super.updateByPrimaryKey(m);
        }
    }

    /**
     * 更新第三方商品池的商品价格信息
     * @param sysplugin
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJDProductPrice(SysPlugin sysplugin, List<MarketProduct> marketProductList){
        // 根据京东商品sku获取价格并保存
        for (MarketProduct m : marketProductList) {
            JDProductInfo jdp = JDServiceUtils.selectJDProductPrice(sysplugin.getAttribute("token"), m.getSkuId());
            if (null != jdp) {
                //市场价
                m.setMarketPrice(new BigDecimal(jdp.getJdPrice()));
                //销售价
                m.setPrice(new BigDecimal(jdp.getPrice()));
                //税率
                String tax = jdp.getTax();
                if (!"0".equals(tax)) {
                    m.setTax(new BigDecimal(tax).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
                } else {
                    m.setTax(new BigDecimal(0));
                }
                //结算价
                m.setCost(new BigDecimal(jdp.getPrice()));
            }
        }
        //更新信息
        for (MarketProduct m : marketProductList) {
            super.updateByPrimaryKey(m);
        }
    }

    /**
     * 更新第三方商品池的商品上下架状态
     * @param sysplugin
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJDProductState(SysPlugin sysplugin, List<MarketProduct> marketProductList){
        //根据京东商品sku获取商品上下架状态
        for (MarketProduct m : marketProductList) {
            JDProductInfo jdp = JDServiceUtils.selectJDProductState(sysplugin.getAttribute("token"), m.getSkuId());
            if (null != jdp) {
                if ("1".equals(jdp.getState())) {
                    m.setIsMarketable(true);
                } else {
                    m.setIsMarketable(false);
                }
            }
        }
        //更新信息
        for (MarketProduct m : marketProductList) {
            super.updateByPrimaryKey(m);
        }
    }

    /**
     * 更新第三方商品池的商品可售性等信息
     * @param sysplugin
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJDProductSaleState(SysPlugin sysplugin, List<MarketProduct> marketProductList){
        //根据京东商品sku获取商品可售性
        for (MarketProduct m : marketProductList) {
            JDProductInfo jdp = JDServiceUtils.selectJDProductSaleState(sysplugin.getAttribute("token"), m.getSkuId());
            if (null != jdp) {
                if ("1".equals(jdp.getSaleState())) {
                    m.setSaleState(true);
                } else {
                    m.setSaleState(false);
                }
            }
        }
        //更新信息
        for (MarketProduct m : marketProductList) {
            super.updateByPrimaryKey(m);
        }
    }

    /**
     * 更新第三方商品池的商品图片等信息
     * @param sysplugin
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJDProductImage(SysPlugin sysplugin, List<MarketProduct> marketProductList){
        //根据京东商品sku获取商品可售性
        for (MarketProduct m : marketProductList) {
            //查询图片信息并保存
            String imageInfo = JDServiceUtils.selectJDProductImage(sysplugin.getAttribute("token"), m.getSkuId());
            if (StringUtils.isNotEmpty(imageInfo)) {
                m.setImage(imageInfo);
                //其他资源
                m.setMeta(JDServiceUtils.getImageMeta(imageInfo, sysplugin.getAttribute("imgPath")));
            }
        }
        //更新信息
        for (MarketProduct m : marketProductList) {
            super.updateByPrimaryKey(m);
        }
    }

    /**
     * 1.调用网易严选api获得网易严选实物商品sku列表，获取第三方商品池已保存的网易严选sku列表
     * 2.对二者进行比较
     * 3.若有，则新增商品sku信息，无则不添加商品信息
     * @param sysplugin
     */
    public void saveWYYXProduct(SysPlugin sysplugin){
        List<String> addSkuList = new ArrayList<String>();
        //商品池获取的网易严选sku列表
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sn", "wyyx-");
        List<String> dbSkuList = selectSkuList(params);
        //查询网易严选的商品sku列表
        List<String> productList = YXOpenApiUtils.selectSku(sysplugin.getAttribute("appKey"), sysplugin.getAttribute("appSecre"));
        if (0 == dbSkuList.size()){
            addSkuList = productList;
        } else {
            addSkuList = YXOpenApiUtils.compareSku(dbSkuList, productList);
        }
        List<MarketProduct> addMarketProductList = new ArrayList<MarketProduct>();
        if (0 < addSkuList.size()) {
            addMarketProductList = getWYYXProducts(sysplugin, addSkuList);
            for (MarketProduct m : addMarketProductList) {
                super.insertUseGeneratedKeys(m);
            }
        }
    }

    /**
     * 获取网易严选商品sku资料
     */
    public List<MarketProduct> getWYYXProducts(SysPlugin sysPlugin, List<String> skuList) {
        //保存的商品信息
        List<MarketProduct> marketProductList = new ArrayList<MarketProduct>();
        Long enterpriseId = 0L;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("name","葫芦派");
        List<Enterprise> enterpriseList= enterpriseService.selectList(param);
        if (0 < enterpriseList.size()) {
            enterpriseId = enterpriseList.get(0).getId();
        }
        Long supplierId = 0L;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name","网易严选");
        List<Supplier> supplierList = supplierService.selectList(params);
        if (0 < supplierList.size()) {
            supplierId = supplierList.get(0).getId();
        }
        for (String sku : skuList) {
            //调用京东获取商品信息接口
            Map<String, Object> map = YXOpenApiUtils.selectWYYXProdectSku(sysPlugin.getAttribute("appKey"), sysPlugin.getAttribute("appSecre"), sku);
            MarketProduct marketProduct = new MarketProduct();
            //创建时间
            marketProduct.setCreateDate(new Date());
            //是否列出
            marketProduct.setIsList(true);
            //是否上架
            marketProduct.setIsMarketable(true);
            //市场价
            marketProduct.setMarketPrice(BigDecimal.ZERO);
            //商品名称
            marketProduct.setName(map.get("name").toString());
            //描述说明
            marketProduct.setSubTitle(map.get("subTitle").toString());
            //销售价
            marketProduct.setPrice(BigDecimal.ZERO);
            //结算价
            marketProduct.setCost((BigDecimal) map.get("price"));
            //税率
            marketProduct.setTax(BigDecimal.ZERO);
            //sn
            marketProduct.setSn("wyyx-" + map.get("skuId").toString());
            //售卖单位
            marketProduct.setUnit("件");
            //单位系数,用默认
            marketProduct.setUnitRate(BigDecimal.ONE);
            //重量
            marketProduct.setWeight(BigDecimal.ZERO);
            //缩略图
            marketProduct.setThumbnail(map.get("thumbnail").toString());
            //类型
            marketProduct.setType(0);
            //保质期
            marketProduct.setQuality(0);
            //商品详情
            marketProduct.setContent(map.get("content").toString());
            //商品详情图
            marketProduct.setWxintroduction("");
            //品牌名称
            marketProduct.setBrandName("网易自营品牌");
            //供应商
            marketProduct.setSupplierId(supplierId);
            //skuid
            marketProduct.setSkuId(map.get("skuId").toString());
            //市场插件id
            marketProduct.setMarketPluginId(sysPlugin.getPluginId());
            //来源商户
            marketProduct.setEnterpriseId(enterpriseId);
            //图片信息
            marketProduct.setImage("");
            //其他资源
            marketProduct.setMeta(map.get("meta").toString());
            marketProductList.add(marketProduct);
        }

        return marketProductList;
    }

    /**
     * 更新已上架至商品库的网易严选商品信息
     * @param sysPlugin
     * @param enterpriseId
     * @param mchId
     * @param productList
     */
    public void updateWYYXProduct(SysPlugin sysPlugin, Long enterpriseId, String mchId, List<Product> productList){
        if (0 < productList.size()) {
            List<SysMsgPush> sysMsgPushList = new ArrayList<SysMsgPush>();
            for (Product p : productList) {
                boolean updateProduct = false;//是否更新p的标志
                boolean offShelfSign = false;//商品下架标识
                Map<String, Object> map = YXOpenApiUtils.selectWYYXProdectSku(sysPlugin.getAttribute("appKey"),
                        sysPlugin.getAttribute("appSecre"), p.getSn().substring(5, p.getSn().length()));

                //名字
                if (!p.getName().equals(map.get("name").toString())) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> content = new HashMap<>();
                        content.put("title", "网易严选商品名称改变");
                        content.put("sku", p.getSn());
                        content.put("name", p.getName());
                        content.put("msg", "每日商品库定时更新，名称由" + p.getName() + "变为" + map.get("name").toString() + ",系统已下架");
                        content.put("supplierName", "网易严选");
                        sysMsgPush.setMsgKey("msg-wangyiyanxuanMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(content));
                        sysMsgPush.setMsgTitle(content.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setName(map.get("name").toString());
                    p.setIsMarketable(false);
                    p.setModifyDate(new Date());
                    offShelfSign = true;
                    updateProduct = true;
                }
                //详情图
                if (!p.getContent().equals(map.get("content").toString())) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> contentMap = new HashMap<>();
                        contentMap.put("title", "网易严选详情图改变");
                        contentMap.put("sku", p.getSn());
                        contentMap.put("name", p.getName());
                        contentMap.put("msg", "每日商品库定时更新，详情图由" + p.getContent() + "变为" + map.get("content").toString() + ",商品详情图已更新");
                        contentMap.put("supplierName", "网易严选");
                        sysMsgPush.setMsgKey("msg-wangyiyanxuanMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                        sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setContent(map.get("content").toString());
                    updateProduct = true;
                }
                //主图
                if (!p.getMeta().equals(map.get("meta").toString())) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> contentMap = new HashMap<>();
                        contentMap.put("title", "网易严选商品主图改变");
                        contentMap.put("sku", p.getSn());
                        contentMap.put("name", p.getName());
                        contentMap.put("msg", "每日商品库定时更新，主图由" + p.getMeta() + "变为" + map.get("meta").toString() + ",商品主图已更新");
                        contentMap.put("supplierName", "网易严选");
                        sysMsgPush.setMsgKey("msg-wangyiyanxuanMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                        sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setMeta(map.get("meta").toString());
                    updateProduct = true;
                }
                //结算价
                if (0 != p.getCost().compareTo(new BigDecimal(map.get("price").toString()))) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> contentMap = new HashMap<>();
                        contentMap.put("title", "网易严选商品结算价改变");
                        contentMap.put("sku", p.getSn());
                        contentMap.put("name", p.getName());
                        contentMap.put("msg", "每日商品库定时更新，结算价由" + p.getCost() + "变为" + map.get("price").toString() + ",系统已下架");
                        contentMap.put("supplierName", "网易严选");
                        sysMsgPush.setMsgKey("msg-wangyiyanxuanMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                        sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    p.setMarketPrice(new BigDecimal(map.get("price").toString()));
                    p.setPrice(new BigDecimal(map.get("price").toString()));
                    p.setCost(new BigDecimal(map.get("price").toString()));
                    p.setIsMarketable(false);
                    p.setModifyDate(new Date());
                    updateProduct = true;
                }
                //库存
                Map<String, Object> stockMap = YXOpenApiUtils.selectWYYXProdectSkuStock(sysPlugin.getAttribute("appKey"),
                        sysPlugin.getAttribute("appSecre"), p.getSn().substring(5, p.getSn().length()));
                BigDecimal stock = (BigDecimal) stockMap.get("stock");
                if (1 == new BigDecimal(100).compareTo(stock)) {
                    if (p.getIsMarketable() && !p.getDeleted()) {
                        SysMsgPush sysMsgPush = new SysMsgPush();
                        sysMsgPush.setId(CodeGenerator.getUUID());
                        sysMsgPush.setIsPush(false);
                        sysMsgPush.setMsgLevel(1);
                        sysMsgPush.setMsgType(4);
                        sysMsgPush.setReadStatus("2");
                        sysMsgPush.setPushStatus("0");
                        sysMsgPush.setMchId(mchId);
                        sysMsgPush.setSendDate(new Date());
                        sysMsgPush.setSendUserId("system");
                        sysMsgPush.setSendUserName("admin");
                        sysMsgPush.setReceiveUserName("system");
                        sysMsgPush.setReceiveUserId("yunyin");
                        sysMsgPush.setIsAttac("0");
                        Map<String, Object> contentMap = new HashMap<>();
                        contentMap.put("title", "网易严选商品库存不足");
                        contentMap.put("sku", p.getSn());
                        contentMap.put("name", p.getName());
                        contentMap.put("msg", "每日商品库定时更新库存不足200,系统已下架");
                        contentMap.put("supplierName", "网易严选");
                        sysMsgPush.setMsgKey("msg-wangyiyanxuanMoudle");
                        sysMsgPush.setMsgContent(JSON.toJSONString(contentMap));
                        sysMsgPush.setMsgTitle(contentMap.get("title").toString());
                        sysMsgPushList.add(sysMsgPush);
                    }
                    //库存不满200直接下架
                    p.setIsMarketable(false);
                    p.setModifyDate(new Date());
                    updateProduct = true;
                } else {
                    p.setStock(100);
                    p.setModifyDate(new Date());
                    updateProduct = true;
                }
                if (updateProduct) {
                    productService.updateByPrimaryKey(p);
                }
            }
            if (0 < sysMsgPushList.size()) {
                for (SysMsgPush msg : sysMsgPushList) {
                    sysMsgPushService.insert(msg);
                }
            }
        }
    }

    /**
     * 更新商品池中的网易严选商品
     * @param sysPlugin
     * @param marketProductList
     */
    public void updateWYYXMarketProduct(SysPlugin sysPlugin, List<MarketProduct> marketProductList){
        for (MarketProduct m : marketProductList) {
            Map<String, Object> map = YXOpenApiUtils.selectWYYXProdectSku(sysPlugin.getAttribute("appKey"), sysPlugin.getAttribute("appSecre"), m.getSkuId());
            if (!m.getName().equals(map.get("name").toString())) {
                m.setName(map.get("name").toString());
            }
            if (!m.getThumbnail().equals(map.get("thumbnail").toString())) {
                m.setThumbnail(map.get("thumbnail").toString());
            }
            if (!m.getContent().equals(map.get("content").toString())) {
                m.setContent(map.get("content").toString());
            }
            if (!m.getMeta().equals(map.get("meta").toString())) {
                m.setMeta(map.get("meta").toString());
            }
            if (0 != m.getCost().compareTo(new BigDecimal(map.get("price").toString()))) {
                m.setCost((BigDecimal) map.get("price"));
            }
        }
        //更新信息
        for (MarketProduct m : marketProductList) {
            super.updateByPrimaryKey(m);
        }
    }

}
